<template>
  <div class="update-scenic-form">
    <a-form
      :model="editForm"
      :rules="editRules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <a-form-item label="景点名称" name="scenicName">
        <a-input v-model:value="editForm.scenicName" placeholder="请输入景点名称" />
      </a-form-item>

      <a-form-item label="景点简介" name="scenicBrief">
        <a-textarea v-model:value="editForm.scenicBrief" placeholder="请输入景点简介" :rows="4" />
      </a-form-item>

      <a-form-item label="景点标签" name="tags">
        <a-select
          v-model:value="editForm.tags"
          mode="multiple"
          placeholder="请选择标签"
          style="width: 100%"
        >
          <a-select-option v-for="tag in availableTags" :key="tag.id" :value="tag.tagName">
            {{ tag.tagName }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="游玩建议" name="tips">
        <a-input v-model:value="editForm.tips" placeholder="请输入游玩建议" />
      </a-form-item>

      <a-form-item label="经度" name="scenicLongitude">
        <a-input-number
          v-model:value="editForm.scenicLongitude"
          placeholder="请输入经度"
          :precision="6"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item label="纬度" name="scenicLatitude">
        <a-input-number
          v-model:value="editForm.scenicLatitude"
          placeholder="请输入纬度"
          :precision="6"
          style="width: 100%"
        />
      </a-form-item>

      <!-- 封面图片编辑 -->
      <a-form-item label="封面图片">
        <div class="image-upload-container">
          <!-- 当前封面图片 -->
          <div v-if="currentCoverImageUrl" class="current-cover-image">
            <div style="margin-bottom: 8px; color: #666; font-size: 14px">当前封面图片：</div>
            <div style="position: relative; display: inline-block">
              <img
                :src="currentCoverImageUrl"
                :alt="scenicData.scenicName"
                style="
                  width: 200px;
                  height: 150px;
                  object-fit: cover;
                  border-radius: 8px;
                  border: 1px solid #d9d9d9;
                "
              />
              <a-button
                size="small"
                danger
                :icon="h(DeleteOutlined)"
                style="position: absolute; top: 4px; right: 4px"
                @click="() => removeCoverImage(false)"
              />
            </div>
          </div>

          <!-- 封面图片上传 -->
          <a-upload
            v-model:file-list="coverImageFileList"
            :before-upload="beforeCoverImageUpload"
            :max-count="1"
            list-type="picture-card"
            accept="image/*"
            @change="handleCoverImageChange"
          >
            <div v-if="!currentCoverImageUrl">
              <UploadOutlined />
              <div style="margin-top: 8px">上传封面图片</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>

      <!-- 景点图片编辑 -->
      <a-form-item label="景点图片">
        <div class="image-upload-container">
          <!-- 当前景点图片 -->
          <div v-if="currentScenicImageUrls.length > 0" class="current-images">
            <div style="margin-bottom: 8px; color: #666; font-size: 14px">当前景点图片：</div>
            <div class="current-images-grid">
              <div
                v-for="(imageUrl, index) in currentScenicImageUrls"
                :key="index"
                class="current-image-item"
              >
                <img :src="imageUrl" :alt="`景点图片${index + 1}`" />
                <a-button
                  size="small"
                  danger
                  :icon="h(DeleteOutlined)"
                  class="delete-image-btn"
                  @click="removeScenicImage(index)"
                />
              </div>
            </div>
          </div>

          <!-- 景点图片上传 -->
          <a-upload
            v-model:file-list="scenicImageFileList"
            :before-upload="beforeScenicImageUpload"
            list-type="picture-card"
            accept="image/*"
            multiple
            @change="handleScenicImageChange"
          >
            <div>
              <UploadOutlined />
              <div style="margin-top: 8px">上传景点图片</div>
            </div>
          </a-upload>
        </div>
      </a-form-item>

      <a-form-item label="更新说明">
        <a-alert
          message="图片更新说明"
          description="• 可以删除现有图片或上传新图片
• 支持 JPG、PNG、WEBP 格式
• 单个图片不超过 2MB
• 保存时会同时更新基本信息和图片"
          type="info"
          show-icon
        />
      </a-form-item>

      <!-- 操作按钮 -->
      <a-form-item :wrapper-col="{ offset: 4, span: 20 }">
        <a-space>
          <a-button
            type="primary"
            @click="handleUpdate"
            :loading="updateLoading"
            :icon="h(SaveOutlined)"
          >
            保存修改
          </a-button>
          <a-button @click="handleCancel" :icon="h(CloseOutlined)"> 取消 </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadFile, UploadChangeParam } from 'ant-design-vue'
import { SaveOutlined, CloseOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { updateScenic } from '@/api/scenicController'
import { listTag } from '@/api/tagController'

// 定义 props 和 emits
interface Props {
  scenicData: API.ScenicVO
}

const props = defineProps<Props>()

const emit = defineEmits<{
  updated: [scenicData: API.ScenicVO]
  cancel: []
  refresh: [scenicId: string] // 新增：请求刷新景点数据
}>()

const updateLoading = ref(false)
const availableTags = ref<API.TagVO[]>([])
const coverImageFileList = ref<UploadFile[]>([])
const scenicImageFileList = ref<UploadFile[]>([])

// 追踪当前显示的图片（可能是原有URL或新上传文件的预览）
const currentCoverImageUrl = ref('')
const currentScenicImageUrls = ref<string[]>([])

// 追踪新上传的文件
const newCoverImageFile = ref<File | null>(null)
const newScenicImageFiles = ref<File[]>([])

// 追踪要保留的原有图片URL（用于发送给后端）
const keepScenicImages = ref<string[]>([])

// 编辑表单数据
const editForm = reactive({
  id: undefined as string | undefined,
  scenicName: '',
  scenicBrief: '',
  tags: [] as string[],
  tips: '',
  scenicLongitude: undefined as number | undefined,
  scenicLatitude: undefined as number | undefined,
})

// 表单验证规则
const editRules = {
  scenicName: [
    { required: true, message: '请输入景点名称', trigger: 'blur' },
    { min: 2, max: 50, message: '景点名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  scenicBrief: [
    { required: true, message: '请输入景点简介', trigger: 'blur' },
    { min: 10, max: 500, message: '景点简介长度在 10 到 500 个字符', trigger: 'blur' },
  ],
  scenicLongitude: [
    { required: true, message: '请输入景点经度', trigger: 'blur' },
    {
      type: 'number',
      min: -180,
      max: 180,
      message: '经度必须在 -180 到 180 之间',
      trigger: 'blur',
    },
  ],
  scenicLatitude: [
    { required: true, message: '请输入景点纬度', trigger: 'blur' },
    { type: 'number', min: -90, max: 90, message: '纬度必须在 -90 到 90 之间', trigger: 'blur' },
  ],
}

// 初始化表单数据
const initializeForm = () => {
  if (!props.scenicData.id) {
    message.error('景点 ID 无效，无法编辑')
    return
  }

  // 初始化编辑表单数据
  editForm.id = props.scenicData.id?.toString()
  editForm.scenicName = props.scenicData.scenicName || ''
  editForm.scenicBrief = props.scenicData.scenicBrief || ''
  editForm.tags = [...(props.scenicData.tags || [])]
  editForm.tips = props.scenicData.tips || ''
  editForm.scenicLongitude = props.scenicData.scenicLongitude ?? undefined
  editForm.scenicLatitude = props.scenicData.scenicLatitude ?? undefined

  // 初始化图片数据 - 确保只保存原始URL，不保存base64数据
  currentCoverImageUrl.value = props.scenicData.coverImage || ''

  // 过滤掉可能的base64数据，只保留真实的URL
  const originalImages = (props.scenicData.scenicImages || []).filter(
    (url) => !url.startsWith('data:'),
  )
  currentScenicImageUrls.value = [...originalImages]
  keepScenicImages.value = [...originalImages]

  // 重置文件列表和新上传文件
  coverImageFileList.value = []
  scenicImageFileList.value = []
  newCoverImageFile.value = null
  newScenicImageFiles.value = []

  console.log('初始化表单 - 原始图片:', originalImages)
  console.log('初始化表单 - keepScenicImages:', keepScenicImages.value)
}

// 获取可用标签
const getAvailableTags = async () => {
  try {
    const res = await listTag({})
    const responseData = res as { data: API.BaseResponseListTagVO }
    if (responseData.data?.code === 200 && responseData.data?.data) {
      availableTags.value = responseData.data.data ?? []
    }
  } catch (error) {
    console.error('获取标签失败:', error)
    message.error('获取标签失败')
  }
}

// 封面图片上传处理
const beforeCoverImageUpload = (file: UploadFile) => {
  console.log('beforeCoverImageUpload 被调用:', {
    name: file.name,
    size: file.size,
    type: file.type,
  })

  const isJpgOrPng =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG/WEBP 格式的图片')
    return false
  }
  const isLt2M = (file.size || 0) / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }

  // 手动处理文件，不让组件自动上传
  // 但也不能直接返回 false，因为这会导致 originFileObj 为空
  // 我们改用直接在这里处理文件的方式
  console.log('手动处理文件对象...')

  // 直接设置文件对象
  const fileObj = file as unknown as File
  newCoverImageFile.value = fileObj

  console.log('在 beforeUpload 中设置文件对象:', {
    name: fileObj.name,
    size: fileObj.size,
    type: fileObj.type,
  })

  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    currentCoverImageUrl.value = e.target?.result as string
    console.log('在 beforeUpload 中创建预览URL完成')
  }
  reader.readAsDataURL(fileObj)

  return false // 阻止自动上传
}

const handleCoverImageChange = (info: UploadChangeParam) => {
  console.log('封面图片change事件:', {
    status: info.file.status,
    fileListLength: info.fileList.length,
    hasOriginFileObj: !!info.file.originFileObj,
    fileName: info.file.name,
  })

  // 如果是删除操作，清空状态
  if (info.file.status === 'removed') {
    console.log('触发删除操作')
    removeCoverImage(true)
    return
  }

  // 如果 beforeUpload 已经处理了文件，这里只需要更新文件列表状态
  // 由于 beforeUpload 返回 false，originFileObj 可能为空，但文件已经在 beforeUpload 中处理
  if (info.fileList.length > 0 && !info.file.originFileObj) {
    console.log('beforeUpload 已处理文件，更新文件列表状态')
    // 更新文件列表状态，但文件对象已经在 beforeUpload 中设置
    coverImageFileList.value = [...info.fileList]
    console.log('文件列表已更新，newCoverImageFile.value:', !!newCoverImageFile.value)
    return
  }

  // 处理新上传的文件（如果 originFileObj 存在）
  if (info.file.originFileObj) {
    console.log('处理新上传的封面图片:', info.file.name, '大小:', info.file.size)

    // 立即设置文件对象 - 确保引用正确
    const fileObj = info.file.originFileObj
    newCoverImageFile.value = fileObj

    console.log('文件对象已设置:', {
      name: fileObj.name,
      size: fileObj.size,
      type: fileObj.type,
      lastModified: fileObj.lastModified,
    })

    // 异步创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      const result = e.target?.result as string
      currentCoverImageUrl.value = result
      console.log('封面图片预览URL已创建，长度:', result.length)

      // 再次确认文件对象还在
      console.log('预览创建后，文件对象状态:', !!newCoverImageFile.value)
    }
    reader.onerror = (error) => {
      console.error('文件读取失败:', error)
    }
    reader.readAsDataURL(fileObj)
  } else {
    console.log('没有找到originFileObj，但可能已在beforeUpload中处理')
  }

  // 总是更新文件列表状态
  coverImageFileList.value = [...info.fileList]

  console.log('handleCoverImageChange结束，newCoverImageFile.value:', !!newCoverImageFile.value)
}

const removeCoverImage = (fromUploadComponent = false) => {
  // 简化删除逻辑：只清空本地显示状态，不影响后端原有数据
  // 用户删除封面图片后，界面不显示，但提交时不传删除参数，后端保持原有
  console.log('=== 删除封面图片操作 ===')
  console.log('删除来源:', fromUploadComponent ? 'Upload组件' : '删除按钮')
  console.log('删除前状态:', {
    hasNewCoverImageFile: !!newCoverImageFile.value,
    hasCoverImageUrl: !!currentCoverImageUrl.value,
    fileListLength: coverImageFileList.value.length,
  })

  currentCoverImageUrl.value = ''
  newCoverImageFile.value = null
  coverImageFileList.value = []

  console.log('删除后状态: 所有封面图片相关状态已清空')
}

// 景点图片上传处理
const beforeScenicImageUpload = (file: UploadFile) => {
  console.log('beforeScenicImageUpload 被调用:', {
    name: file.name,
    size: file.size,
    type: file.type,
  })

  const isJpgOrPng =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG/WEBP 格式的图片')
    return false
  }
  const isLt2M = (file.size || 0) / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return false // 阻止自动上传，我们在 change 事件中手动处理
}

const handleScenicImageChange = (info: UploadChangeParam) => {
  // 更新文件列表显示
  scenicImageFileList.value = [...info.fileList]

  // 提取有效的文件对象
  newScenicImageFiles.value = info.fileList
    .filter((file) => file.originFileObj)
    .map((file) => file.originFileObj!) as File[]

  // 重新构建当前显示的图片URL数组
  // 先添加保留的原有图片URL（不是base64数据）
  currentScenicImageUrls.value = [...keepScenicImages.value]

  // 为新上传的文件创建预览URL并添加到显示列表
  newScenicImageFiles.value.forEach((file: File) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const imageUrl = e.target?.result as string
      // 只将base64数据添加到显示列表，不影响keepScenicImages
      if (!currentScenicImageUrls.value.includes(imageUrl)) {
        currentScenicImageUrls.value.push(imageUrl)
      }
    }
    reader.readAsDataURL(file)
  })
}

const removeScenicImage = (index: number) => {
  // 获取要删除的图片URL
  const deletedImageUrl = currentScenicImageUrls.value[index]

  // 判断删除的是原有图片还是新上传的图片
  const originalImageUrls = props.scenicData.scenicImages || []

  // 检查是否为原始图片URL（不是base64数据）
  if (originalImageUrls.includes(deletedImageUrl) && !deletedImageUrl.startsWith('data:')) {
    // 删除的是原有图片，从保留列表中移除
    const keepIndex = keepScenicImages.value.indexOf(deletedImageUrl)
    if (keepIndex > -1) {
      keepScenicImages.value.splice(keepIndex, 1)
    }
  } else {
    // 删除的是新上传的图片（base64数据）
    // 找到在新上传文件列表中的索引
    const base64Images = currentScenicImageUrls.value.filter((url) => url.startsWith('data:'))
    const base64Index = base64Images.indexOf(deletedImageUrl)

    if (base64Index > -1 && base64Index < newScenicImageFiles.value.length) {
      // 从新上传文件列表中移除
      newScenicImageFiles.value.splice(base64Index, 1)

      // 从文件上传组件的文件列表中移除对应项
      const fileListIndex = scenicImageFileList.value.findIndex(
        (file, idx) => idx === base64Index && file.originFileObj,
      )
      if (fileListIndex > -1) {
        scenicImageFileList.value.splice(fileListIndex, 1)
      }
    }
  }

  // 从当前显示列表中删除
  currentScenicImageUrls.value.splice(index, 1)
}

// 处理更新（包含图片）
const handleUpdate = async () => {
  updateLoading.value = true

  try {
    // 验证必填字段
    if (!editForm.scenicName || editForm.scenicName.trim() === '') {
      message.error('景点名称不能为空')
      return
    }

    if (!editForm.scenicBrief || editForm.scenicBrief.trim() === '') {
      message.error('景点简介不能为空')
      return
    }

    if (editForm.scenicLongitude === undefined || editForm.scenicLatitude === undefined) {
      message.error('经纬度不能为空')
      return
    }

    // 构建更新参数 - 简化封面图片逻辑：有新图片就传，无则不传
    let coverImageToSend: File | undefined = undefined

    // 提交前最终状态检查
    console.log('=== 提交前封面图片状态检查 ===')
    console.log('newCoverImageFile.value:', newCoverImageFile.value)
    console.log(
      'currentCoverImageUrl.value:',
      currentCoverImageUrl.value ? '有预览URL' : '无预览URL',
    )
    console.log('coverImageFileList.value:', coverImageFileList.value)

    if (newCoverImageFile.value) {
      // 有新上传的封面图片就传
      coverImageToSend = newCoverImageFile.value
      console.log('✅ 准备发送封面图片:', {
        name: coverImageToSend.name,
        size: coverImageToSend.size,
        type: coverImageToSend.type,
        lastModified: coverImageToSend.lastModified,
      })
    } else {
      console.log('❌ 没有新的封面图片需要发送')
      // 如果有预览URL但没有文件对象，这是异常状态
      if (currentCoverImageUrl.value && currentCoverImageUrl.value.startsWith('data:')) {
        console.error('⚠️ 异常状态：有base64预览但没有文件对象！')
      }
    }
    // 没有新图片就不传，后端保持原有封面图片不变

    const updateParams: API.updateScenicParams = {
      id: editForm.id,
      scenicName: editForm.scenicName.trim(),
      scenicBrief: editForm.scenicBrief.trim(),
      tags: editForm.tags || [],
      tips: editForm.tips || '',
      scenicLongitude: editForm.scenicLongitude,
      scenicLatitude: editForm.scenicLatitude,
      coverImage: coverImageToSend,
      scenicImages: newScenicImageFiles.value.length > 0 ? newScenicImageFiles.value : undefined,
      keepScenicImages: keepScenicImages.value.length > 0 ? keepScenicImages.value : undefined,
    }

    console.log('=== 最终更新参数 ===', {
      id: updateParams.id,
      scenicName: updateParams.scenicName,
      coverImage: newCoverImageFile.value ? `文件对象: ${newCoverImageFile.value.name}` : '无',
      hasNewCoverImage: !!newCoverImageFile.value,
      newCoverImageFileExists: newCoverImageFile.value !== null,
      originalCoverImage: props.scenicData.coverImage,
      currentCoverImageUrl: currentCoverImageUrl.value ? '有预览URL' : '无预览URL',
      coverImageFileListLength: coverImageFileList.value.length,
      scenicImagesCount: newScenicImageFiles.value.length,
      keepScenicImagesCount: keepScenicImages.value.length,
    })

    console.log('🚀 调用 updateScenic API...')

    const response = await updateScenic(updateParams)

    if (response.data.code === 200 && response.data.data) {
      message.success('景点信息更新成功！')

      console.log('🔄 请求刷新景点数据...')
      // 请求父组件刷新景点数据，确保获取到最新的信息
      emit('refresh', editForm.id!)

      // 同时构建更新后的景点数据作为备用（如果父组件不支持刷新）
      // 确保图片URL是真实的URL而不是base64数据
      const updatedScenicImages = currentScenicImageUrls.value.filter(
        (url) => !url.startsWith('data:'),
      )

      // 封面图片逻辑：如果传了新图片，使用新图片；否则保持原有
      const updatedCoverImage = newCoverImageFile.value
        ? currentCoverImageUrl.value && !currentCoverImageUrl.value.startsWith('data:')
          ? currentCoverImageUrl.value
          : props.scenicData.coverImage
        : props.scenicData.coverImage // 没有新图片时，保持原有封面图片

      const updatedScenicData: API.ScenicVO = {
        ...props.scenicData,
        scenicName: updateParams.scenicName,
        scenicBrief: updateParams.scenicBrief,
        tags: updateParams.tags,
        tips: updateParams.tips,
        scenicLongitude: updateParams.scenicLongitude,
        scenicLatitude: updateParams.scenicLatitude,
        coverImage: updatedCoverImage,
        scenicImages:
          updatedScenicImages.length > 0 ? updatedScenicImages : props.scenicData.scenicImages,
        updateTime: new Date().toISOString(),
      }

      console.log('📤 发送更新事件作为备用方案:', updatedScenicData)
      emit('updated', updatedScenicData)
    } else {
      message.error('更新失败：' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('请求失败:', error)
    message.error('更新失败，请稍后再试')
  } finally {
    updateLoading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('cancel')
}

// 监听 scenicData 变化，重新初始化表单
watch(
  () => props.scenicData,
  () => {
    initializeForm()
  },
  { immediate: true, deep: true },
)

// 组件挂载时获取标签
onMounted(() => {
  getAvailableTags()
})
</script>

<style scoped>
.update-scenic-form {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.image-upload-container {
  width: 100%;
}

.current-cover-image {
  margin-bottom: 16px;
  text-align: center;
}

.current-images {
  margin-bottom: 16px;
}

.current-images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.current-image-item {
  position: relative;
  width: 120px;
  height: 90px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
}

.current-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-image-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.delete-image-btn:hover {
  background: rgba(255, 255, 255, 1);
  color: #ff4d4f;
}
</style>
